package com.chendk.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by Capc on 2017/6/12.
 */
@Aspect
@Component
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(public * com.chendk.controller..*(..))")
    public void logPointCut() {
    }

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Before("logPointCut()")
    public void doHttpLogBefore(JoinPoint joinPoint) throws Throwable{
        // 接收到请求，记录请求内容
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("Request-start::" + request.getRequestURI() + "----" + System.currentTimeMillis());
        logger.info("IP::" + request.getRemoteAddr());
        logger.info("CLASS_METHOD::" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS::" + Arrays.toString(joinPoint.getArgs()));
        logger.info("HTTP_METHOD :: " + request.getMethod());
    }

    @AfterReturning(returning ="retParam" , pointcut = "logPointCut()")
    public void doHttpLogAfterReturning(Object retParam) throws Throwable{
        // 接收到请求，记录请求内容
        logger.info("Response::" + retParam);
        logger.info("Spend_time::"  + (System.currentTimeMillis() - startTime.get()));
    }
}
